package com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.repository.HddcGeologicalsvypointNativeRepository;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.repository.HddcGeologicalsvypointRepository;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.repository.entity.HddcGeologicalsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.service.HddcGeologicalsvypointService;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.viewobjects.HddcGeologicalsvypointPageVO;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.viewobjects.HddcGeologicalsvypointQueryParams;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.viewobjects.HddcGeologicalsvypointVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author lihelei
 * @date 2020-11-27
 */
@Service
public class HddcGeologicalsvypointServiceImpl implements HddcGeologicalsvypointService {

	@Autowired
    private HddcGeologicalsvypointRepository hddcGeologicalsvypointRepository;
    @Autowired
    private HddcGeologicalsvypointNativeRepository hddcGeologicalsvypointNativeRepository;

    @Override
    public JSONObject queryHddcGeologicalsvypoints(HddcGeologicalsvypointQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcGeologicalsvypointPageVO> hddcGeologicalsvypointPage = this.hddcGeologicalsvypointNativeRepository.queryHddcGeologicalsvypoints(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcGeologicalsvypointPage);
    }


    @Override
    public HddcGeologicalsvypointEntity getHddcGeologicalsvypoint(String id) {
        return this.hddcGeologicalsvypointRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeologicalsvypointEntity saveHddcGeologicalsvypoint(HddcGeologicalsvypointEntity hddcGeologicalsvypoint) {
        String uuid = UUIDGenerator.getUUID();
        hddcGeologicalsvypoint.setUuid(uuid);
        hddcGeologicalsvypoint.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcGeologicalsvypoint.setCreateTime(now);
        hddcGeologicalsvypoint.setUpdateTime(now);
        hddcGeologicalsvypoint.setIsValid(PlatformConstants.Y);
        hddcGeologicalsvypoint.setQualityinspectionStatus(PlatformConstants.N);
        hddcGeologicalsvypoint.setExtends10(PlatformConstants.Y);
        this.hddcGeologicalsvypointRepository.save(hddcGeologicalsvypoint);
        return hddcGeologicalsvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeologicalsvypointEntity updateHddcGeologicalsvypoint(HddcGeologicalsvypointEntity hddcGeologicalsvypoint) {
        HddcGeologicalsvypointEntity entity = hddcGeologicalsvypointRepository.findById(hddcGeologicalsvypoint.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcGeologicalsvypoint);
        hddcGeologicalsvypoint.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcGeologicalsvypoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcGeologicalsvypointRepository.save(hddcGeologicalsvypoint);
        return hddcGeologicalsvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcGeologicalsvypoints(List<String> ids) {
        List<HddcGeologicalsvypointEntity> hddcGeologicalsvypointList = this.hddcGeologicalsvypointRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcGeologicalsvypointList) && hddcGeologicalsvypointList.size() > 0) {
            for(HddcGeologicalsvypointEntity hddcGeologicalsvypoint : hddcGeologicalsvypointList) {
                hddcGeologicalsvypoint.setIsValid("0");
                hddcGeologicalsvypoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeologicalsvypoint.setUpdateTime(new Date());
                this.hddcGeologicalsvypointRepository.save(hddcGeologicalsvypoint);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcGeologicalsvypointQueryParams queryParams, HttpServletResponse response) {
        List<HddcGeologicalsvypointEntity> yhDisasterEntities = hddcGeologicalsvypointNativeRepository.exportYhDisasters(queryParams);
        List<HddcGeologicalsvypointVO> list=new ArrayList<>();
        for (HddcGeologicalsvypointEntity entity:yhDisasterEntities) {
            HddcGeologicalsvypointVO yhDisasterVO=new HddcGeologicalsvypointVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "地质调查观测点-点", "地质调查观测点-点", HddcGeologicalsvypointVO.class, "地质调查观测点-点.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            //params.setTitleRows(1);
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcGeologicalsvypointVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcGeologicalsvypointVO.class, params);
            List<HddcGeologicalsvypointVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcGeologicalsvypointVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcGeologicalsvypointVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcGeologicalsvypointVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcGeologicalsvypointEntity yhDisasterEntity = new HddcGeologicalsvypointEntity();
            HddcGeologicalsvypointVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcGeologicalsvypoint(yhDisasterEntity);
        }
    }


    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcGeologicalsvypointEntity> hddcGeologicalsvypointList = this.hddcGeologicalsvypointRepository.queryHddcGeologicalsvypointsByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcGeologicalsvypointList) && hddcGeologicalsvypointList.size() > 0) {
            for(HddcGeologicalsvypointEntity hddcGeologicalsvypoint : hddcGeologicalsvypointList) {
                hddcGeologicalsvypoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeologicalsvypoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGeologicalsvypoint.setIsValid("0");
                this.hddcGeologicalsvypointRepository.save(hddcGeologicalsvypoint);
            }
        }
    }

    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcGeologicalsvypointEntity> hddcGeologicalsvypointList = this.hddcGeologicalsvypointRepository.queryHddcGeologicalsvypointsByTaskId(taskIds);
        if(!PlatformObjectUtils.isEmpty(hddcGeologicalsvypointList) && hddcGeologicalsvypointList.size() > 0) {
            for(HddcGeologicalsvypointEntity hddcGeologicalsvypoint : hddcGeologicalsvypointList) {
                hddcGeologicalsvypoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeologicalsvypoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGeologicalsvypoint.setIsValid("0");
                this.hddcGeologicalsvypointRepository.save(hddcGeologicalsvypoint);
            }
        }
    }
}


